import {constantRoutes} from '@/router'
import {getRouters} from '@/api/menu'
import Layout from '@/layout/index'
import View from '@/layout/components/View'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    indexPage: '',
    basePath: '',
  },
  // getters: {
  //   indexPage: state => state.indexPage
  // },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_INDEX_PAGE: (state, routes) => {
      state.indexPage = routes
    },
    SET_ACTIVE_ROUTE: (state, activeRoute) => {
      state.activeRoute = activeRoute
    },
    SET_BASE_PATH: (state, basePath) => {
      state.basePath = basePath
    },
    SET_IS_SECONED_CHECKED: (state, isSecondChecked) => {
      state.isSecondChecked = isSecondChecked
    },
  },
  actions: {
    // 生成路由
    // GenerateRoutes({commit}) {
    //   return new Promise((resolve) => {
    //     // 向后端请求路由数据
    //     getRouters().then((res) => {
    //       // 删除2.0错误路由
    //       if (res.data[0].path == '/operateCenter') {
    //         res.data.shift()
    //       }
    //       const accessedRoutes = filterAsyncRouter(res.data)
    //       accessedRoutes.push({path: '*', redirect: '/404', hidden: true})
    //       const firstPage = res.data[0].path + "/" + res.data[0].children[0].path;
    //       console.log(firstPage, 'firstPage')
    //       commit('SET_ROUTES', accessedRoutes)
    //       commit('SET_INDEX_PAGE', firstPage)
    //       resolve(accessedRoutes)
    //     })
    //   })
    // }
    GenerateRoutes({commit}) {
      return new Promise((resolve, reject) => {
        // 向后端请求路由数据
        getRouters()
          .then((res) => {
            if (res.data && res.data.length > 0) {
              // 删除2.0错误路由
              if (res.data[0].path === '/operateCenter') {
                res.data.shift();
              }
              const accessedRoutes = filterAsyncRouter(res.data);
              accessedRoutes.push({path: '*', redirect: '/404', hidden: true});
              console.log('accessedRoutes:::::::', accessedRoutes,  accessedRoutes[0].path, accessedRoutes[0].children)
              const firstPage = accessedRoutes[0].children?.[0].path ? accessedRoutes[0].path + "/" + accessedRoutes[0].children[0].path : accessedRoutes[0].path;
              console.log(firstPage, 'firstPage');
              commit('SET_ROUTES', accessedRoutes);
              commit('SET_INDEX_PAGE', firstPage);
              resolve(accessedRoutes);
            } else {
              reject(new Error('No data received from server'));
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
let level = 0

function filterAsyncRouter(asyncRouterMap) {
  level++
  let res = asyncRouterMap.filter((route) => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        if (route.redirect === 'noRedirect' && route.children.length) {
          route.redirect = route.path + '/' + route.children[0].path
        }
        if (level != 1) {
          route.component = View
        } else {
          route.component = Layout
        }
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  level--
  return res
}

export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
